package me.ereach;

import java.io.*;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        if (args.length != 2) {
            System.out.println("必须提供输入和输出文件的名称！如: in.txt out.txt");
            return;
        }

        File file1 = new File(args[0]);
        if (!file1.exists()) {
            System.out.println("输入文件不存在! " + file1.getAbsolutePath());
            return;
        }

        File file2 = new File(args[1]);
        if (file2.exists()) {
            file2.delete();
            System.out.println("旧的输出文件已被删除. " + args[1]);
        }

        file2.createNewFile();
        FileOutputStream fop = new FileOutputStream(file2, true);

        System.out.println("输入文件是 " + file1.getAbsolutePath());
        System.out.println("输入文件的分隔符必须是制表符 \\t\n");

        try(BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
            for(String line; (line = br.readLine()) != null; ) {
                List<String> lst = processLine(line);

                Integer total = 0;
                for (int i = 1; i < 6; i++) {
                    total += Integer.parseInt(lst.get(i));
                }

                String grd = "";
                if (total >= 95)
                    grd = "A";
                else if (total >= 90)
                    grd = "A-";
                else if (total >= 85)
                    grd = "B";
                else if (total >= 80)
                    grd = "B-";
                else if (total >= 75)
                    grd = "C";
                else if (total >= 70)
                    grd = "C-";
                else if (total >= 65)
                    grd = "D";
                else if (total >= 60)
                    grd = "D-";
                else
                    grd = "E";

                String newLine = lst.get(0) + "\t" + total.toString() + "\t" + grd + "\r\n";
                fop.write(newLine.getBytes());
                System.out.print("写入行：" + newLine);
            }
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
        finally {
            fop.flush();
            fop.close();
        }

        System.out.println("\n请检查输出文件：" + file2.getAbsolutePath());
    }

    static List<String> processLine(String line) {
        return Arrays.asList(line.split("\t"));
    }
}
